import { Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from 'redis';

@Injectable()
export class RedisService {
    @Inject('REDIS_CLIENT')
    private readonly redis: RedisClientType;

    async get(key: string) {
        return await this.redis.get(key);
    }
    async set(key: string, value: string | number, ttl?: number) {
        await this.redis.set(key, value);
        if (ttl) {
            //设置过期时间
            await this.expire(key, ttl);
        }
    }

    // 删除单个键
    async del(key: string) {
        await this.redis.del(key);
    }

    async getTtl(key: string): Promise<number | null> {
        try {
            // 使用 ttl 命令获取剩余过期时间（秒）
            const remainingSeconds = await this.redis.ttl(key);
            if (remainingSeconds >= 0) {
                return remainingSeconds;
            }

            // 如果需要毫秒级精度，可以使用 pttl 命令
            // const remainingMilliseconds = await this.client.pttl(key);
            // if (remainingMilliseconds >= 0) {
            //   return remainingMilliseconds;
            // }

            return null;
        } catch (error) {
            console.error('Error getting remaining time:', error);
            return null;
        }
    }

    async expire(key: string, ttl: number) {
        await this.redis.expire(key, ttl);
    }
}
